package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.core.content.ContextCompat
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.rxui.tablayout.listener.GlideEngine
import com.gexiaobao.pigeon.app.util.MeSandboxFileEngine
import com.gexiaobao.pigeon.app.util.PictureUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityAddCarInfoBinding
import com.gexiaobao.pigeon.ui.view.LicensePlateView
import com.gexiaobao.pigeon.viewmodel.DrippingViewModel
import com.google.gson.Gson
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.zs.easy.imgcompress.EasyImgCompress
import com.zs.easy.imgcompress.listener.OnCompressSinglePicListener
import com.zs.easy.imgcompress.util.GBMBKBUtil
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File


/**
 * @Author      : hxw
 * @Date        : 2024/6/20 8:22
 * @Describe    : 添加车辆
 */
class ActivityAddCarInfo : BaseActivity<DrippingViewModel, ActivityAddCarInfoBinding>(), LicensePlateView.InputListener {

    private var type: String = ""
    private var carPictureFile: File? = null
    private var drivingFile: File? = null
    private var mLicensePlateType = false
    private var mLicensePlateNumber = ""
    private var mOrgId = 0
    private var mBaseInfoId = 0
    private var isInputComplete = false

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "添加车辆信息"
        mOrgId = intent.getIntExtra("orgId", 0)
        type = intent.getStringExtra("type").toString()
        if (type != "ActivityCarInfo" && type != "ActivityOrderSquare") {
            mBaseInfoId = intent.getIntExtra("baseInfoId", 0)
        }

        mDatabind.licensePlateView.hideLastView()
        mDatabind.licensePlateView.setInputListener(this)
        mDatabind.licensePlateView.setKeyboardContainerLayout(mDatabind.conContainer)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack, mDatabind.tvSubmitCarInfo, mDatabind.ivCarPicture, mDatabind.ivDrivingPicture,
            mDatabind.tvLicensePlateType
        ) {
            when (it) {
                mDatabind.tvLicensePlateType -> {
                    if (!mLicensePlateType) {
                        isInputComplete = false
                        mDatabind.licensePlateView.showLastView()
                        mDatabind.tvLicensePlateType.text = "普"
                        mDatabind.tvLicensePlateType.setTextColor(ContextCompat.getColor(this, R.color.bg_light_bllue))
                        mDatabind.tvLicensePlateType.background = ContextCompat.getDrawable(this, R.drawable.border_blue)
                    } else {
                        mDatabind.licensePlateView.hideLastView()
                        mDatabind.tvLicensePlateType.text = "新"
                        mDatabind.tvLicensePlateType.setTextColor(ContextCompat.getColor(this, R.color.green_37d35d))
                        mDatabind.tvLicensePlateType.background = ContextCompat.getDrawable(this, R.drawable.border_green)
                    }
                    mLicensePlateType = !mLicensePlateType
                }

                mDatabind.ivCarPicture -> {
                    selectPicture(1)
                }

                mDatabind.ivDrivingPicture -> {
                    selectPicture(2)
                }

                mDatabind.tvSubmitCarInfo -> {
                    submitCarInfo()
                }

                mDatabind.includeBar.ivBack -> {
                    finish()
                }
            }
        }
    }

    private fun selectPicture(type: Int) {//1-车辆正面照 2-行驶证
        val selectionModel: PictureSelectionModel = PictureSelector.create(this)
            .openGallery(SelectMimeType.ofImage())
            .setSelectorUIStyle(PictureSelectorStyle())
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(PictureUtil.getCompressFileEngine())
            .setSandboxFileEngine(MeSandboxFileEngine())
            .setSelectionMode(SelectModeConfig.SINGLE)
            .setCameraInterceptListener(PictureUtil.getCustomCameraEvent())
            .setPermissionDescriptionListener(PictureUtil.getPermissionDescriptionListener())
            .setPreviewInterceptListener(PictureUtil.getPreviewInterceptListener())
            .setPermissionDeniedListener(PictureUtil.getPermissionDeniedListener())
            .setQueryFilterListener { false }
            .isLoopAutoVideoPlay(false)
            .isPageSyncAlbumCount(true)
            .setLanguage(LanguageConfig.SYSTEM_LANGUAGE)
            .setQuerySortOrder("")
            .isDisplayCamera(true)
            .isOpenClickSound(false)
            .isPreviewImage(true)
            .isMaxSelectEnabledMask(true)
            .isDirectReturnSingle(true)
        selectionModel.forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: ArrayList<LocalMedia>?) {
                val path = result!![0].realPath
                val bitmap = BitmapFactory.decodeFile(path)
                compressedPicture(path, type)
                when (type) {
                    1 -> {
                        mDatabind.ivCarPicture.setImageBitmap(bitmap)
                    }

                    else -> {
                        mDatabind.ivDrivingPicture.setImageBitmap(bitmap)

                    }
                }
            }

            override fun onCancel() {}
        })
    }

    private fun compressedPicture(path: String?, type: Int) {
        /** 把单张图片压缩到1024k以内 同时像素不超过1200（宽、高都不大于1200） */
        EasyImgCompress.withSinglePic(this@ActivityAddCarInfo, path)
            .maxPx(1200)
            .maxSize(1024)
            .enableLog(true)
            .setOnCompressSinglePicListener(object : OnCompressSinglePicListener {
                override fun onStart() {
                    LogUtils.debugInfo("onStart")
                }

                override fun onSuccess(file: File) {
                    when (type) {
                        1 -> {
                            carPictureFile = file
                        }

                        else -> {
                            drivingFile = file
                        }
                    }
                    LogUtils.debugInfo("onSuccess size = " + GBMBKBUtil.getSize(file.length()) + " getAbsolutePath= " + file.absolutePath)
                }

                override fun onError(error: String) {
                    LogUtils.warnInfo("onError error = $error")
                }
            }).start()
    }

    private fun submitCarInfo() {
        if (mDatabind.licensePlateView.editContent == null) {
            RxToast.warning("未填写车牌号")
            return
        }
        mLicensePlateNumber = mDatabind.licensePlateView.editContent
        when {
            !isInputComplete -> RxToast.warning("请输入正确的车牌号")
            carPictureFile == null -> RxToast.warning("未上传车辆正面照")
            drivingFile == null -> RxToast.warning("未上传行驶证")
            else -> {
                showLoading(getString(R.string.loading))
                val map = mapOf(
                    "licensePlateNumber" to mLicensePlateNumber,
                    "licensePlate" to carPictureFile,
                    "travelCard" to drivingFile
                )
                mViewModel.addTransporterApplyCar(map)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 接鸽员申请中关于汽车的信息创建（用户角色） */
        mViewModel.addCarResult.observe(this) {
            if (type == "ActivityCarInfo" || type == "ActivityOrderSquare") {
                RxToast.showToast("添加成功")
                eventViewModel.toRefreshDataStr.value = "ActivityAddCarInfo"
                finish()
                return@observe
            }
            val map = mapOf("orgId" to mOrgId, "baseInfoId" to mBaseInfoId, "carInfoId" to it.id)
            val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
            mViewModel.addTransporterApply(body)
        }
        /**  申请成为接鸽员（用户角色） */
        mViewModel.applyPigeonCatcherResult.observe(this) {
            eventViewModel.toRefreshDataStr.value = "ActivityAddCarInfo"
            RxToast.success("申请成功")
            finish()
        }
    }

    override fun inputComplete(p0: String?) {
        isInputComplete = !p0.isNullOrEmpty()
        LogUtils.debugInfo(p0)
    }

    override fun deleteContent() {
        isInputComplete = false
        LogUtils.debugInfo("deleteContent")
    }
}